#include <graphics.h>
#include <conio.h>
#include <stdio.h>

#define WIDTH 800
#define HEIGHT 600

int main()
{
	initgraph(WIDTH, HEIGHT); // 新开一个画面
	BeginBatchDraw();	//批量绘制

	// 小球
	float x = WIDTH / 6;
	float y = HEIGHT / 3;
	float g = 0.3f;
	float vy = 0;
	int radius = 20;

	// 矩阵
	float blockWidth = radius * 2;
	float xBlockLeft = WIDTH * 0.8;
	float xBlockRight = xBlockLeft + blockWidth;
	float gapHeight = HEIGHT / 2;
	float yGapTop = HEIGHT / 3;
	float yGapBottom = yGapTop + gapHeight;
	int xBlockV = 3;

	// 分数
	int score = 0;

	while (true)
	{
		// 先判断再输出
		if (_kbhit())
		{
			char input = _getch();
			if (input == ' ')
			{
				// 向上的力量
				vy -= 10;
			}
		}

		// 计算位置
		vy += g;
		y += vy;
		
		xBlockLeft -= xBlockV;
		xBlockRight = xBlockLeft + blockWidth;

		// 位置判断
		if (y <= radius || y >= HEIGHT - radius)
		{
			y = HEIGHT / 3;
			vy = 0;
			score = 0;
			gapHeight = HEIGHT / 2;
			xBlockV = 3;
		}
		if (xBlockLeft < 0)
		{
			// 产生变化
			xBlockLeft = WIDTH;
			xBlockRight = xBlockLeft + blockWidth;
			yGapTop = rand() % (HEIGHT / 2);
			yGapBottom = yGapTop + gapHeight;
			score++;

			if (score % 2 == 0 && gapHeight > radius * 4)
			{
				xBlockV *= 2;
				gapHeight -= radius;
			}
		}

		// 判断是否碰撞
		if (
			(x + radius > xBlockLeft && x - radius < xBlockRight) &&
			(y - radius<yGapTop || y + radius>yGapBottom)
			)
		{
			xBlockV = 3;
			gapHeight = HEIGHT / 2;
			score = 0;
			Sleep(20);
		}

		cleardevice(); // 清屏
		// 输出小球
		fillcircle(x, y, radius);
		fillrectangle(xBlockLeft, 0, xBlockRight, yGapTop);
		fillrectangle(xBlockLeft, yGapBottom, xBlockRight, HEIGHT);

		// 输出字符
		TCHAR s[20];
		swprintf_s(s, _T("%d"), score);
		settextstyle(40, 0, _T("宋体"));
		outtextxy(50, 30, s);

		FlushBatchDraw();
		Sleep(3);
	}

	return 0;
}